import React, {
  useCallback,
  useEffect,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import TextAtom from "../../Atoms/Text.Atom";
import TextAtomEnum from "../../Atoms/Text.Atom/enum";
import ButtonAtom from "../../Atoms/Button.Atom";
import ButtonAtomEnum from "../../Atoms/Button.Atom/enum";
import { SortSelectProps } from "./type";

const SortSelect: React.FC<SortSelectProps> = (props) => {
  const { items, applyFilters, filters, filterKey } = props;
  const [isOpen, setIsOpen] = useState(false);
  const [selectedItem, setSelectedItem] = useState(items?.[0]?.title);

  const toggleDropdown = () => setIsOpen(!isOpen);

  const handleSelect = useCallback(
    (item: { title: string; value: string }) => {
      applyFilters({ ...filters, [filterKey]: item.value });
      setSelectedItem(item.title);
      setIsOpen(false);
    },
    [applyFilters, filterKey, filters]
  );

  useEffect(() => {
    const selectedItemFromFilters = items?.find(
      (item) => item.value === filters?.[filterKey]
    );
    if (selectedItemFromFilters) {
      setSelectedItem(selectedItemFromFilters.title);
    }
  }, [filters, items, filterKey]);

  const renderItems = useMemo(
    () =>
      items?.map((item, index) => (
        <ButtonAtom
          type={ButtonAtomEnum.enum_defaultButton}
          onClick={() =>
            handleSelect({
              ...item,
              title: item.title ?? "",
              value: item.value ?? "",
            })
          }
          key={index}
          className="cursor-pointer w-full text-left p-2 hover:bg-borderColor text-textColor"
        >
          <TextAtom type={TextAtomEnum.enum_h5}>{item.title}</TextAtom>
        </ButtonAtom>
      )),
    [handleSelect, items]
  );

  const menuRef = useRef<HTMLDivElement>(null);

  const handleClickOutside = useCallback((event: MouseEvent) => {
    if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
      setIsOpen(false);
    }
  }, []);

  useLayoutEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [handleClickOutside]);

  return (
    <div
      ref={menuRef}
      onClick={toggleDropdown}
      className="flex cursor-pointer relative flex-col gap-2 py-2 px-3 rounded border-[1px] border-gray border-solid hover:border-bg_hover text-textColor"
    >
      <TextAtom
        type={TextAtomEnum.enum_h4}
        className="text-textColor font-medium"
      >
        {selectedItem}
      </TextAtom>
      {isOpen && (
        <div className="absolute top-[40px] left-0 w-60 bg-bgGen rounded-lg border-[2px] border-borderColor shadow-sm z-20">
          {renderItems}
        </div>
      )}
    </div>
  );
};
export default React.memo(SortSelect);
